package org.rox.hephantan.bai3;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;

public class Server {
	public static void main(String[] args) {
		ServerSocket serverSocket;
		Socket socket;
		Boolean listening = true;
		String data;
		try {
			serverSocket = new ServerSocket(2002);
			System.out.println("Server is listening..");
			socket = serverSocket.accept();
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));			
			PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
			while(listening) {
				data = reader.readLine();
				System.out.println("Data received from Client: " + data);
				//treat data, then send it back to Client				
				writer.println(countWords(data));
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	static int countWords(String data) {
		StringTokenizer st = new StringTokenizer(data, " ");
		int count = st.countTokens();
		return count;
	}
}
